package com.aurora_manito.xiaomi.utils;

import org.springframework.http.HttpRequest;

import javax.jws.WebService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;


public class BaseServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //判断用户行为
        String methodName=req.getParameter("method");
        //利用反射调用
        try {
            Method method=this.getClass().getMethod(methodName,HttpServletRequest.class,HttpServletResponse.class);
            //重定向
            String  url=(String)method.invoke(this,req,resp);
            if(url!=null&&url.trim().length()!=0)
            {
                //转发
                if(url.startsWith("redirect:"))
                {
                    //截取字符串
                    resp.sendRedirect(req.getContextPath()+url.split(":")[1]);
                }else {
                    //重定期
                    req.getRequestDispatcher(url).forward(req, resp);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       this.doPost(req,resp);
    }

}
